package com.province.platform.core.assign;

import com.province.platform.common.utils.Configuration;
import com.province.platform.core.constants.CoreConstants;
import org.apache.commons.lang3.Validate;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public abstract class AbstractAssign {
    private Configuration configuration;

    private int channelNumber;

    private int taskGroupChannel;

    public AbstractAssign(Configuration configuration, int channelNumber, int taskGroupChannel) {
        this.configuration = configuration;
        this.channelNumber = channelNumber;
        this.taskGroupChannel = taskGroupChannel;
    }

    public List<Configuration> getTaskGroupConfigs() {
        List<Configuration> contentConfig = this.configuration.getListConfiguration(CoreConstants.JOB_CONTENT);
        Validate.isTrue(!contentConfig.isEmpty(), "框架获得的切分后的 Job 无内容.");

        Configuration taskGroupTemplate = this.configuration.clone();
        taskGroupTemplate.remove(CoreConstants.JOB_CONTENT);

        int taskGroupNumber = (int) Math.ceil(1.0 * channelNumber / taskGroupChannel);
        List<List<Configuration>> taskGroupConfigList = new ArrayList<>(taskGroupNumber);
        for (int i = 0; i < taskGroupNumber; i++) {
            taskGroupConfigList.add(new LinkedList<>());
        }

        doAssign(contentConfig, taskGroupConfigList, taskGroupNumber);

        Configuration tempTaskConfiguration;
        List<Configuration> taskGroupConfigs = new LinkedList<>();
        for (int i = 0; i < taskGroupNumber; i++) {
            tempTaskConfiguration = taskGroupTemplate.clone();
            tempTaskConfiguration.set(CoreConstants.JOB_CONTENT, taskGroupConfigList.get(i));
            tempTaskConfiguration.set(CoreConstants.CORE_CONTAINER_TASK_GROUP_ID, i);
            taskGroupConfigs.add(tempTaskConfiguration);
        }

        return taskGroupConfigs;
    }

    protected abstract void doAssign(List<Configuration> contentConfig, List<List<Configuration>> taskGroupConfigList, int taskGroupNumber);
}
